package com.tsing.mvc.interceptor;

import com.tsing.mvc.util.AddressUtils;
import com.tsing.mvc.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对ip 进行限制，防止IP大量请求
 *
 * IP拦截i
 */
@Slf4j
@Configuration
public class IpUrlLimitInterceptor implements HandlerInterceptor {


    /**
     * 请求被处理之前进行操作，COntroller方法之前调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {

        //通过本地获取
/*//        获得ip
        String ip = IPUtil.getIpAddr(httpServletRequest);
//        解析具体地址
        String addr = IPUtil.getAddr("2.58.179.255");
        log.info("IP >> {},Address >> {}", ip, addr);*/

        //通过在线库获取
/*        String ip2 = IPUtil.getIpAddr(httpServletRequest);
        String ipaddr2 = AddressUtils.getRealAddressByIP(ip2);
        log.info("IP >> {},Address >> {}", ip2, ipaddr2);*/
        return true;
    }

    /**
     * 当前请求进行处理之后，也就是Controller 方法调用之后执行，但是它会在DispatcherServlet进行视图返回渲染之前被调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {

    }

    /**
     *  该方法将在整个请求结束之后，也就是在DispatcherServlet 渲染了对应的视图之后执行
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

    }
}
